package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.dto.RoleDTO;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.constants.DyRoleKeyConstants;
import com.ruoyi.system.domain.vo.DyAnchorVo;
import com.ruoyi.system.mapper.DyAnchorMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.IDyCommonService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.DyGoodsBo;
import com.ruoyi.system.domain.vo.DyGoodsVo;
import com.ruoyi.system.domain.DyGoods;
import com.ruoyi.system.mapper.DyGoodsMapper;
import com.ruoyi.system.service.IDyGoodsService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 商品Service业务层处理
 *
 * @author ruoyi
 * @date 2024-06-20
 */
@RequiredArgsConstructor
@Service
public class DyGoodsServiceImpl implements IDyGoodsService {

    private final DyGoodsMapper baseMapper;

    private final DyAnchorMapper dyAnchorMapper;

    private final SysUserMapper sysUserMapper;

    @Autowired
    IDyCommonService iDyCommonService;

    /**
     * 查询商品
     */
    @Override
    public DyGoodsVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询商品列表
     */
    @Override
    public TableDataInfo<DyGoodsVo> queryPageList(DyGoodsBo bo, PageQuery pageQuery, LoginUser loginUser) {
        RoleDTO roleDTO = iDyCommonService.getFirstRole(loginUser.getRoles());
        if (ObjectUtil.isEmpty(roleDTO)){
            throw new ServiceException("无数据查看权限");
        }

        LambdaQueryWrapper<DyGoods> lqw = buildQueryWrapper(bo);

        if (roleDTO.getRoleKey().equals(DyRoleKeyConstants.roleKeySubCompany)){
            LambdaQueryWrapper<SysUser> queryWrapperUser = new LambdaQueryWrapper<>();
            queryWrapperUser.eq(SysUser::getDeptId,loginUser.getDeptId());
            List<SysUser> userList = sysUserMapper.selectList(queryWrapperUser);
            lqw.in(DyGoods::getAnchorId,userList);
        }

        lqw.orderByDesc(DyGoods::getUpdateTime);
        Page<DyGoodsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollectionUtil.isNotEmpty(result.getRecords())){
            List<Long> authorIds = result.getRecords().stream().map(DyGoodsVo::getAnchorId).collect(Collectors.toList());
            List<DyAnchorVo> anchorVos = dyAnchorMapper.selectVoBatchIds(authorIds);
            Map<Long,DyAnchorVo> anchorMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(anchorVos)){
                anchorMap = anchorVos.stream().collect(Collectors.toMap(DyAnchorVo::getId,item -> item,(k1,k2) -> k1));
            }
            for (DyGoodsVo item : result.getRecords()){
                if (ObjectUtil.isNotEmpty(anchorMap.get(item.getAnchorId())) && ObjectUtil.isNotEmpty(anchorMap.get(item.getAnchorId()).getName())){
                    item.setAnchorName(anchorMap.get(item.getAnchorId()).getName());
                }
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询商品列表
     */
    @Override
    public List<DyGoodsVo> queryList(DyGoodsBo bo) {
        LambdaQueryWrapper<DyGoods> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DyGoods> buildQueryWrapper(DyGoodsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DyGoods> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), DyGoods::getName, bo.getName());
        lqw.eq(bo.getAnchorId() != null, DyGoods::getAnchorId, bo.getAnchorId());
        lqw.eq(bo.getAmount() != null, DyGoods::getAmount, bo.getAmount());
        lqw.eq(StringUtils.isNotBlank(bo.getImg()), DyGoods::getImg, bo.getImg());
        return lqw;
    }

    /**
     * 新增商品
     */
    @Override
    public Boolean insertByBo(DyGoodsBo bo) {
        DyGoods add = BeanUtil.toBean(bo, DyGoods.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改商品
     */
    @Override
    public Boolean updateByBo(DyGoodsBo bo) {
        DyGoods update = BeanUtil.toBean(bo, DyGoods.class);
        validEntityBeforeEdit(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeEdit(DyGoods entity){
        if (ObjectUtil.isEmpty(entity.getId())){
            throw new ServiceException("参数错误!");
        }
    }

    /**
     * 批量删除商品
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
